// component/tvideocall2/tvideocall2.js
import TRTC from "../tvideocall2/trtc-wx"
import {
  randomRoomID
} from "../tvideocall2/common"
const app = getApp();
Component({
  options: {
    pureDataPattern: /^_/ // 指定所有 _ 开头的数据字段为纯数据字段
  },
  /**
   * 组件的属性列表
   */
  properties: {

  },

  /**
   * 组件的初始数据
   */
  data: {
    _bigVideoIndex: 0, //大窗口的索引，默认是第0个，即pusher
    //小窗口的宽高
    _littleWidth: 75,
    _littleHeight: 100,
    //player列表
    videoList: [{
        width: '100%',
        height: '100%',
        //move-view在area的位置
        x: 0,
        y: 0,
        type: "pusher", //视频类型
        direction: 'all', //可移动的方向
        styleClass: 'mv-big', //大窗口的样式
        videoData: {}, //视频数据
      },
      // {
      //   width: '75px',
      //   height: '100px',
      //   x: app.globalData.systemInfo.windowWidth - 1 * 75,
      //   y: 0,
      //   type: "player",
      //   direction: 'all',
      //   styleClass: 'mv-little', //小窗口样式
      //   videoData: {}, //视频数据
      // },
    ],
    //可视窗口的宽度
    windowWidth: app.globalData.systemInfo.windowWidth, //可视窗口的宽度
    /**------------------------------音视频api相关参数----------------------------------------- */
    _rtcConfig: {
      sdkAppID: '', // 必要参数 开通实时音视频服务创建应用后分配的 sdkAppID
      userID: '', // 必要参数 用户 ID 可以由您的帐号系统指定
      userSig: '', // 必要参数 身份签名，相当于登录密码的作用
    },
    _rtcEvents: {
      onLocalJoin: "onLocalJoin",
      onError: "onError",
    },
  },
  lifetimes: {
    attached: function () {
      let pageInstance = this;
      // setInterval(() => {
      //   if (pageInstance.data.videoList.length < 10) {
      //     pageInstance.onVideoListAdd();
      //     clearInterval();
      //   }
      // }, 1000 * 3);
      //保持屏幕常亮
      wx.setKeepScreenOn({
        keepScreenOn: true,
      })
    },
    detached: function () {},
  },
  /**
   * 组件的方法列表
   */
  methods: {

    /**-----------------------------------------------窗口变化----------------------------------------------------- */
    /**
     * move-view 移动时触发此事件，此时需要将videoList内的x y更改
     */
    onMvChange(event) {
      const {
        index,
        type
      } = event.currentTarget.dataset;
      const {
        x,
        y
      } = event.detail;
      console.log(x, y);
      this.data.videoList[index].x = x;
      this.data.videoList[index].y = y;
    },
    /**
     * 点击小窗口
     * @param {} event 
     */
    onClickVideo(event) {
      let pageInstance = this;
      const {
        type,
        index,
      } = event.currentTarget.dataset;

      if (type == "mv-little") {
        //先拼接id
        let viewId = '#' + type + index;
        //点击小窗口，执行切换
        const query = this.createSelectorQuery();
        query.select(viewId).boundingClientRect();
        query.exec(function (res) {
          const {
            _bigVideoIndex,
            videoList: _videoList
          } = pageInstance.data;
          const left = res[0].left;
          const top = res[0].top;
          //执行变换
          _videoList[_bigVideoIndex].width = '75px';
          _videoList[_bigVideoIndex].height = '100px';
          _videoList[_bigVideoIndex].x = left;
          _videoList[_bigVideoIndex].y = top;
          _videoList[_bigVideoIndex].direction = 'all';
          _videoList[_bigVideoIndex].styleClass = 'mv-little';

          _videoList[index].width = '100%';
          _videoList[index].height = '100%';
          _videoList[index].x = '0';
          _videoList[index].y = '0';
          _videoList[index].direction = 'all';
          _videoList[index].styleClass = 'mv-big';

          pageInstance._bigVideoIndex = index;
          pageInstance.setData({
            videoList: _videoList,
            _bigVideoIndex: index
          })

        });
      } else {}
    },

    /**
     * 测试方法：有新用户进房间，列表数据的改变，此时应该遍历列表，然后更新视频数据
     */
    onVideoListAdd() {
      const {
        videoList: _videoList
      } = this.data;
      let playerList = [{
          streamId: '6544'
        }, {
          streamId: '549887'
        },
        {
          streamId: '75464'
        }
      ];
      let player = {
        id: '75464'
      };
      //view是3行3列的格式
      for (let i = 0; i < playerList.length; i++) {
        //是新添加的player,添加到videoList去
        if (playerList[i].streamId == player.id) {
          let _x = app.globalData.systemInfo.windowWidth - ((_videoList.length - 1) % 3 + 1) * 75;
          let _y = Number.parseInt((_videoList.length - 1) / 3) * 100;
          _videoList.push({
            width: '75px',
            height: '100px',
            x: _x,
            y: _y,
            type: "player",
            direction: 'all',
            styleClass: 'mv-little', //小窗口样式
            videoData: {
              streamId: '75464'
            }, //视频数据
          })
        }
      }
      this.setData({
        videoList: _videoList
      })
    },


    /** ----------------------------------音视频相关方法------------------------------------------ */

    /**
     * 通过Players更新videoList
     */
    updateVideosByPlayers(playerList) {
      const {
        _videoList
      } = this.data;
      for (let i = 1; i < _videoList.length; i++) {
        let isHave = false;
        for (let j = 0; j < playerList; j++) {
          if (_videoList[i].videoData.id == playerList[j].id) {
            isHave = true;
            _videoList[i].videoData = playerList[j];
          }
        }
        if (!isHave) {
          _videoList.pop(i);
        }
      }
      return _videoList;
    },

    /**
     * 初始化方法
     * @param {页面实例} pageInstance 
     * @param {rtc配置} rtcConfig 
     */
    init(pageInstance, rtcConfig) {
      //初始化TRTC实例
      this.TRTC = new TRTC(pageInstance);
      // pusher 初始化参数
      const pusherConfig = {
        beautyLevel: 0,
        mode: "RTC"
      };
      //创建推流实例对象，此时并未进入房间
      const pusher = this.TRTC.createPusher(pusherConfig);
      this.data.videoList[0].videoData = pusher.pusherAttributes
      // videoList里第一个是必存在的pusher
      let _videoList = this.data.videoList[0].videoData;
      this.setData({
        _rtcConfig: rtcConfig,
        videoList: _videoList
      });
      // 绑定监听事件
      this.methods.bindTRTCRoomEvent();
    },
    /**
     * 进入房间，不开始推流，如果进入房间就立即推流请调用startPushLocal方法
     */
    enterRoom(roomId) {
      const roomID = roomId || randomRoomID()
      const config = Object.assign(this.data._rtcConfig, {
        roomID
      });
      const {
        _videoList
      } = this.data;
      _videoList[0].videoData = this.TRTC.enterRoom(config);
      this.setData({
        videoList: _videoList
      })
    },
    /**
     * 退出房间
     */
    exitRoom() {
      const result = this.TRTC.exitRoom();
      let newVideoList = this.methods.updateVideosByPlayers(result.playerList);
      newVideoList[0].videoData = result.pusher;
      this.setData({
        videoList: newVideoList,
      })
    },

    /**
     * 屏蔽players的声音
     */
    enableAudioPlayers(muteAudio) {
      for (let i = 1; i < this.data.videoList.length; i++) {
        let player = this.data.videoList[i].videoData;
        this.methods.setPlayerAttributesHandler(player, {
          muteAudio: muteAudio
        });
      }
    },
    /**
     * 本地麦克风控制
     */
    enableMic(enableMic) {
      this.methods.setPusherAttributesHandler({
        enableMic: enableMic
      })
    },




    // 设置 pusher 属性
    setPusherAttributesHandler(options) {
      let pusher = this.TRTC.setPusherAttributes(options);
      const {
        videoList: _videoList
      } = this.data;
      _videoList[0].videoData = pusher;
      this.setData({
        videoList: _videoList
      })
    },

    // 设置某个 player 属性
    setPlayerAttributesHandler(player, options) {
      let playerList = this.TRTC.setPlayerAttributes(player.streamID, options);
      let newVideos = this.methods.updateVideosByPlayers(playerList);
      this.setData({
        videoList: newVideos
      })
    },
    /**
     * 绑定事件监听 pusher player
     */
    bindTRTCRoomEvent() {
      const TRTC_EVENT = this.TRTC.EVENT;
      const {
        _rtcEvents
      } = this.data;
      //进房成功的监听
      this.TRTC.on(TRTC_EVENT.LOCAL_JOIN, (event) => {
        this.triggerEvent(_rtcEvents.onLocalJoin, {
          event: event
        });
        // 进房成功，触发该事件后可以对本地视频和音频进行设置
        this.methods.setPusherAttributesHandler({
          enableCamera: true, //打开相机
        });
        this.methods.setPusherAttributesHandler({
          enableMic: true, //打开话筒
        });
      });
      //离开房间了
      this.TRTC.on(TRTC_EVENT.LOCAL_LEAVE, (event) => {
        console.log('* room LOCAL_LEAVE', event)
      })
      //错误监听
      this.TRTC.on(TRTC_EVENT.ERROR, (event) => {
        this.triggerEvent(_rtcEvents.onError, {
          event: event
        });
      });

      // 远端用户退出
      this.TRTC.on(TRTC_EVENT.REMOTE_USER_LEAVE, (event) => {
        const {
          playerList
        } = event.data
        let newVideos = this.methods.updateVideosByPlayers(playerList);
        this.setData({
          videoList: newVideos
        })
      });
      // 远端用户推送视频
      this.TRTC.on(TRTC_EVENT.REMOTE_VIDEO_ADD, (event) => {
        console.log('* room REMOTE_VIDEO_ADD', event)
        const {
          player
        } = event.data
        // 开始播放远端的视频流，默认是不播放的
        this.methods.setPlayerAttributesHandler(player, {
          muteVideo: false
        })
      });
      // 远端用户取消推送视频
      this.TRTC.on(TRTC_EVENT.REMOTE_VIDEO_REMOVE, (event) => {
        console.log('* room REMOTE_VIDEO_REMOVE', event)
        const {
          player
        } = event.data
        this.methods.setPlayerAttributesHandler(player, {
          muteVideo: true
        })
      });
      // 远端用户推送音频 
      this.TRTC.on(TRTC_EVENT.REMOTE_AUDIO_ADD, (event) => {
        console.log('* room REMOTE_AUDIO_ADD', event)
        const {
          player
        } = event.data
         //默认不主动拉音频流，需要您手动进行订阅
        this.methods.setPlayerAttributesHandler(player, {
          muteAudio: false
        })
      })
      // 远端用户取消推送音频
      this.TRTC.on(TRTC_EVENT.REMOTE_AUDIO_REMOVE, (event) => {
        console.log('* room REMOTE_AUDIO_REMOVE', event)
        const {
          player
        } = event.data
        this.methods.setPlayerAttributesHandler(player, {
          muteAudio: true
        })
      })
    },

    /**
     * 开始推流，同时开启摄像头预览
     */
    startPushLocal() {
      this.TRTC.getPusherInstance().start(); // 开始推流（autoPush的模式下不需要）
    },
    /**
     * 停止推流，同时停止摄像头预览
     */
    stopPushLocal() {
      this.TRTC.getPusherInstance().stop();
    },
    /**
     * 开始摄像头预览画面
     */
    startPreviewLocal() {
      this.TRTC.getPusherInstance().startPreview();
    },
    /**
     * 停止摄像头预览画面
     */
    stopPreviewLocal() {
      this.TRTC.getPusherInstance().stopPreview();
    },

    // live-pusher和live-player的相关绑定方法:请保持跟 wxml 中绑定的事件名称一致
    _pusherStateChangeHandler(event) {
      this.TRTC.pusherEventHandler(event)
    },
    _pusherNetStatusHandler(event) {
      this.TRTC.pusherNetStatusHandler(event)
    },
    _pusherErrorHandler(event) {
      this.TRTC.pusherErrorHandler(event)
    },
    _pusherBGMStartHandler(event) {
      this.TRTC.pusherBGMStartHandler(event)
    },
    _pusherBGMProgressHandler(event) {
      this.TRTC.pusherBGMProgressHandler(event)
    },
    _pusherBGMCompleteHandler(event) {
      this.TRTC.pusherBGMCompleteHandler(event)
    },
    _pusherAudioVolumeNotify(event) {
      this.TRTC.pusherAudioVolumeNotify(event)
    },
    _playerStateChange(event) {
      this.TRTC.playerEventHandler(event)
    },
    _playerFullscreenChange(event) {
      this.TRTC.playerFullscreenChange(event)
    },
    _playerNetStatus(event) {
      this.TRTC.playerNetStatus(event)
    },
    _playerAudioVolumeNotify(event) {
      this.TRTC.playerAudioVolumeNotify(event)
    },
  },

})
